import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: 'http://localhost:8991/jiai',
  timeout: 20 * 1000,
})

request.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = 'application/json'
    config.headers['Access-Control-Allow-Origin'] = '*'
    config.headers['Access-Control-Allow-Headers'] =
      'Origin, X-Requested-With, Content-Type, Accept'

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    let res = response.data
    const status = Number(response.status)
    const message = response.data.msg
    if (status !== 200 || res.code === 1) {
      ElMessage({
        message: message,
        type: 'error',
      })
      return Promise.reject(new Error(message))
    }
    if (response.config.responseType === 'blob') {
      return res
    }

    if (typeof res === 'string') {
      res = res ? JSON.parse(res) : res
    }
    return res
  },
  (error) => {
    console.log('error.response' + error.response)
    // 处理 503 网络异常
    if (error.response.code) {
      ElMessage({
        message: error.response.data.msg,
        type: 'error',
      })
    }
    return Promise.reject(error)
  }
)
export default request
